package com.atguigu.day06;

import com.atguigu.utils.ProductViewCountPerWindow;
import com.atguigu.utils.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;

public class Example8 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<UserBehavior> stream = env
                .readTextFile("/home/zuoyuan/flinktutorial0411/src/main/resources/UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String in) throws Exception {
                        String[] array = in.split(",");
                        return new UserBehavior(
                                array[0], array[1], array[2], array[3],
                                Long.parseLong(array[4]) * 1000L
                        );
                    }
                })
                .filter(r -> r.type.equals("pv"))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                );

        stream
                .keyBy(r -> "userbehavior")
                .process(new TopN(3))
                .print();

        env.execute();
    }

    public static class TopN extends KeyedProcessFunction<String, UserBehavior, String> {
        private int n;

        public TopN(int n) {
            this.n = n;
        }

        HashMap<String, Long> pidCount = new HashMap<>();

        @Override
        public void processElement(UserBehavior in, Context ctx, Collector<String> out) throws Exception {
            if (!pidCount.containsKey(in.productId)) {
                pidCount.put(in.productId, 1L);
            } else {
                pidCount.put(in.productId, pidCount.get(in.productId) + 1L);
            }

            ctx.timerService().registerEventTimeTimer(Long.MAX_VALUE);
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            ArrayList<Tuple2<String, Long>> arrayList = new ArrayList<>();

            for (String pid : pidCount.keySet()) {
                arrayList.add(Tuple2.of(pid, pidCount.get(pid)));
            }

            arrayList.sort(new Comparator<Tuple2<String, Long>>() {
                @Override
                public int compare(Tuple2<String, Long> t1, Tuple2<String, Long> t2) {
                    return (int)(t2.f1 - t1.f1);
                }
            });

            StringBuilder result = new StringBuilder();
            result.append("========================================\n");
            for (int i = 0; i < n; i++) {
                result.append("第" + (i+1) + "名的商品：" + arrayList.get(i).f0 + "，浏览次数：" + arrayList.get(i).f1 + "\n");
            }
            result.append("========================================\n");
            out.collect(result.toString());
        }
    }
}
